import { createStore } from "vuex";
import Cookies from "js-cookie";
import * as types from "./mutation-types";

export default createStore({
  state: {
    userId: "",
    userTeamId: "",
    userMobile: "",
    token: "",
    username: "",
    READING_TIME: "",
    START_ANSWER_TIME: "",
    END_ANSWER_TIME: "",
  },
  getters: {},
  mutations: {
    [types.SET_USER_INFO](state, userInfo) {
      state.userId = userInfo.userId;
      state.userTeamId = userInfo.teamId;
      state.userMobile = userInfo.mobile;
      state.token = userInfo.token;
      state.username = userInfo.username;
      Cookies.set("user-info", JSON.stringify(userInfo));
    },
    [types.GET_USER_INFO](state) {
      const userInfoStr = Cookies.get("user-info");
      const userInfo = JSON.parse(userInfoStr || "{}");
      if (userInfo) {
        state.userId = userInfo.userId ?? "";
        state.userTeamId = userInfo.teamId ?? "";
        state.userMobile = userInfo.mobile;
        state.token = userInfo.token;
        state.username = userInfo.username;
        Cookies.set("user-info", JSON.stringify(userInfo));
      }
    },
    [types.SET_TIME_RANGE](state, timeRange) {
      state.READING_TIME = timeRange.readingTime;
      state.START_ANSWER_TIME = timeRange.startAnswerTime;
      state.END_ANSWER_TIME = timeRange.endAnswerTime;
    },
  },
  actions: {},
  modules: {},
});
